/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */
"use strict";
$(function () {
    org.breezee.page = {
        init: function () {
            var loginCustomerId = $("#_loginCustomerId").val();
            var loginAccountId = $("#_loginAccountId").val();
            if(loginCustomerId != null && loginCustomerId != ""){

                var optionUrl="/api/c666378c5d3b417d8e150c456a489d23@accountId="+loginAccountId;
                var ajaxType="get"
                var optionParam='{"properties":{}}'
                $("#customer_select").attr("optionUrl",optionUrl)
                    .attr("ajaxType",ajaxType)
                    .attr("optionParam", optionParam);

            }else{
                var optionUrl="/api/742445c653654caaa4a1fa69eb651a9a"
                var ajaxType="post"
                var optionParam = '{"properties":{"category":"1"}}';
                $("#customer_select").attr("optionUrl",optionUrl)
                    .attr("ajaxType",ajaxType)
                    .attr("optionParam", optionParam);
            }
            Dolphin.form.parse();
            this.initHistoryList();
            this.initEvent();
            var queryObj = {
                customerId: org.breezee.context.userData.customerId,
                _day: '1',
                _busiHourFilter : '1'
            }
            if ($("#isFilterShow").val() == '-1') {
                queryObj.status_not_equal = '2';
                // queryObj.status = '1';
                $("#status").val('1,0');
            }
            Dolphin.ajax({
                url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                type: Dolphin.requestMethod.POST,
                data: Dolphin.json2string({properties : { "selectCustomerId" : loginCustomerId , "selectShopType" : ''}}),
                async: false,
                loading:true,
                onSuccess: function (reData) {
                    if(reData.rows){
                        var shopIdArray = $.map(reData.rows,function(n){
                            return n.id;
                        });
                        queryObj._areaId = shopIdArray.join('-');
                    }
                }
            });
            this._userList = this.userList('#userList',queryObj);
        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            let me = this;
            /**
             * 绑定回车事件，触发搜索
             */
            $(document).keypress(function(e) {
                var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
                if (eCode == 13){
                    $(".btn-query").click();
                }
            });

            $(".newAccount").click(function () {
                Dolphin.form.empty('.edit-form');
                Dolphin.form.setValue({
                    type:'dtk3',
                    recordPeriod:'10',
                    uploadPeriod:'30',
                    level:'5'
                }, '.edit-form');
                $('#account_win').modal('show');
            });

            /**
             * 保存按钮
             */
            $(".btn_submit").click(function () {
                let ef = $(".edit-form");
                if (Dolphin.form.validate(ef)) {
                    let data = Dolphin.form.getValue(ef, '"');
                    Dolphin.ajax({
                        url: '/api/b6a1808e4fcd4844836eb802249ac30c',
                        type: Dolphin.requestMethod.PUT,
                        data: Dolphin.json2string(data),
                        onSuccess: function (reData) {
                            me._userList.load();
                            $('#account_win').modal('hide');
                        }
                    });

                }
            });
            $('.content-refresh').click(function () {
                me._userList.reload();
            });
            //导出
            $(".btn-export").click(function () {

                var shopIds = '';
                var shopAreaCondition = $("#customer_select").val()|| $("#_loginCustomerId").val();//查询条件 区域


                if( shopAreaCondition != null && shopAreaCondition.length > 0 ){
                    Dolphin.ajax({
                        url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                        type: Dolphin.requestMethod.POST,
                        data: Dolphin.json2string({properties : { "selectCustomerId" : shopAreaCondition , "selectShopType" : ''}}),
                        async: false,
                        loading:true,
                        onSuccess: function (reData) {
                            if(reData.rows){
                                var shopIdArray = $.map(reData.rows,function(n){
                                    return n.id;
                                });
                                shopIds = shopIdArray.join('-');
                            }
                        }
                    });
                }
                var queryCondition = Dolphin.form.getValue('.query-form');
                me._userList.opts.queryParams._busiHourFilter = "1";
                me._userList.opts.queryParams.isQuery="true";//是否为设备查询
                if(!$("#customer_select").val() && $("#shopType").val()){
                    delete me._userList.opts.queryParams._areaId;
                }else{
                    queryCondition._areaId = shopIds;
                }

                if (me._userList.opts.queryParams.status_not_equal) {
                    delete me._userList.opts.queryParams.status_not_equal;
                }

                var url = (org.breezee.context.contextPath=='/'?'':org.breezee.context.contextPath) +'/api/08dd4548faa14d3ba3c32d5099b775f3';
                var form = $("<form />");
                form.attr({"style": "display: none", "target": '_blank', "method": "post", "action": url});
                $('body').append(form);
                $.each(me._userList.opts.queryParams, function(key, value){
                    var input = $("<input>");
                    input.attr({"name": key, "value": value, "type": "hidden"});
                    console.log('key : '+key+' | value : '+value);
                    form.append(input);
                });
                form.submit();
                form.remove();
            });

            //查询
            $(".btn-query").click(function () {
                var shopIds = '';
                var shopAreaCondition = $("#customer_select").val()|| $("#_loginCustomerId").val();//查询条件 区域
                if( shopAreaCondition != null && shopAreaCondition.length > 0 ){
                    Dolphin.ajax({
                        url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                        type: Dolphin.requestMethod.POST,
                        data: Dolphin.json2string({properties : { "selectCustomerId" : shopAreaCondition , "selectShopType" : ''}}),
                        async: false,
                        loading:true,
                        onSuccess: function (reData) {
                            if(reData.rows){
                                var shopIdArray = $.map(reData.rows,function(n){
                                    return n.id;
                                });
                                shopIds = shopIdArray.join('-');
                            }
                        }
                    });
                }

                var queryCondition = Dolphin.form.getValue('.query-form');
                me._userList.opts.queryParams._busiHourFilter = "1";
                if(!$("#customer_select").val() && $("#shopType").val()){
                    delete me._userList.opts.queryParams._areaId;
                }else{
                    queryCondition._areaId = shopIds;
                }

                if (me._userList.opts.queryParams.status_not_equal) {
                    delete me._userList.opts.queryParams.status_not_equal;
                }
                me._userList.load('', queryCondition);
            });
        },

        initHistoryList: function () {
            let me = this;
            $('#historyList').empty();
            this._historyList = new Dolphin.LIST({
                panel: '#historyList',
                idField: 'id',
                queryParams:{
                    status : 1
                },
                columns: [{
                    code: 'sn',
                    title: Dolphin.i18n.get("framework.equipmentCode")
                },{
                    code: 'happenTime',
                    title: Dolphin.i18n.get("sales.occurrenceTime"),
                    formatter:function (val) {
                        if(val.length==19){
                            return val;
                        }else{
                            val = val+"";
                            return val.substring(0,4)+"-"+val.substring(4,6)+"-"+val.substring(6,8)+" "
                                +val.substring(8,10)+":"+val.substring(10,12)+":"+val.substring(12,14);
                        }

                    }
                }, {
                    code: 'createdDate',
                    title: Dolphin.i18n.get("framework.latestTime"),
                }, {
                    code: 'dxin',
                    title: Dolphin.i18n.get("equipment.entry"),
                },{
                    code: 'dxout',
                    title: Dolphin.i18n.get("equipment.exit"),
                },{
                    code: 'focus',
                    title: Dolphin.i18n.get("equipment.looseFocusOrNot"),
                    formatter: function (val, row) {
                        return val ? Dolphin.i18n.get("equipment.looseFocus") : Dolphin.i18n.get("equipment.normal");
                    }
                }, {
                    code: 'battery',
                    title: Dolphin.i18n.get("framework.powerVolumn"),
                    formatter: function (val, row) {
                        return val ? val+'%' : '-' ;
                    }
                }],
                multiple: false,
                rowIndex: true,
                checkbox: false,
                pagination: true,
                ajaxType: Dolphin.requestMethod.POST,
                onLoadSuccess: function (data) {
                }
            });
        },

        userList: function (panelId,queryParams) {
            let me = this, colors = ['yellow', 'red', 'green'];
            $(panelId).empty();
            return new Dolphin.LIST({
                panel: panelId,
                queryParams: queryParams,
                idField: 'id',
                columns: [{
                    code: 'province',
                    title: Dolphin.i18n.get("framework.province"),
                    width:'75px'
                }, {
                    code: 'city',
                    title: Dolphin.i18n.get("framework.city"),
                    width:'75px'
                },{
                    code: 'code',
                    title: Dolphin.i18n.get("equipment.equipmentCode"),
                }, {
                    code: 'customerName',
                    title: Dolphin.i18n.get("store.name"),
                    width: '200px'
                }, {
                    code: 'statusName',
                    title: Dolphin.i18n.get("framework.net"),
                    width:'95px',
                    formatter:function (val,row) {
                        var statusVal = (row.status == 1 ? 1 : 2);
                        var statusText = (row.status == 1 ? Dolphin.i18n.get("equipment.offLine") : Dolphin.i18n.get("equipment.normal"));
                        return '<i class="fa fa-circle" aria-hidden="true" style="margin-right: 10px;color:' + colors[statusVal] + ';"></i>' + statusText;
                    }
                }, {
                    code: 'focus',
                    title: Dolphin.i18n.get("framework.focusing"),
                    width:'85px',
                    formatter:function (val,row) {
                        if (row.status != 1) {
                            let v = val ? Dolphin.i18n.get("equipment.looseFocus") : Dolphin.i18n.get("equipment.normal");
                            return '<i class="fa fa-circle" aria-hidden="true" style="margin-right: 10px;' + (row.focus == 1 ? 'color: red;' : 'color: green;') + '"></i>' + v;
                        }else{
                            return "-";
                        }

                    }
                }, {
                    code: 'voltage',
                    title: Dolphin.i18n.get("equipment.batteryCapacity"),
                    width:'90px',
                    formatter:function (val,row) {
                        if (row.status != 1) {
                            return '<i class="fa fa-circle" aria-hidden="true" style="margin-right: 10px;' + (val < 10 ? 'color: red;' : 'color: green;') + '"></i>' + val + '%';
                        } else {
                            return '-'
                        }
                    }
                }, {
                    code: 'lastReceiveTime',
                    title: Dolphin.i18n.get("framework.latestTime"),
                    width:'200px',
                    formatter:function (val) {
                        return val?Dolphin.longDate2string(val,'yyyy-MM-dd hh:mm:ss'):'-';
                    }
                }, {
                    code: 'properties.dxIn',
                    title: Dolphin.i18n.get("equipment.totalIntradayEntry"),
                    width:'100px',
                    formatter:function (val) {
                        return val ? val : '0';
                    }
                }, {
                    code: 'properties.dxOut',
                    title: Dolphin.i18n.get("equipment.toalIntradayExit"),
                    width:'100px',
                    formatter:function (val) {
                        return val ? val : '0';
                    }
                }, {
                    code: 'id',
                    title: '&nbsp;',
                    width: '180px',
                    formatter: function (val, row, index) {

                        var s = '';
                        s += '<a class="btn btn-outline btn-circle btn-sm btn-margin dark historyBtn" ';
                        s += 'data-id' + '="' + row.id + '"';
                        s += ' href="javascript:;"><i class="fa fa-history"></i>&nbsp;'+ Dolphin.i18n.get("equipment.history")+'</a>';

                        return org.breezee.buttons.view({
                                id: row.id
                            })+s ;
                    }
                }],
                multiple: false,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                url: '/api/4e149d0fb488470fb3e493ade50564b6',
                pagination: true,
                onLoadSuccess: function () {
                    org.breezee.buttons.viewCallback('a7b6f1f193a2446d9a5579885a62e60f', 'id', function (data) {
                        $('#account_win').modal('show');
                        $("#myShopSel").val(data.value.customerId);
                    });
                    //查看历史记录
                    $(".historyBtn").click(function () {

                        var deviceId = $(this).data('id');
                        var condition = {'device_id_obj_ae' : deviceId};
                        me._historyList.load('/api/871d375052dc47689a208e66aae04d3a', condition);
                        $('#historyModal').modal('show');

                    });
                }
            });
        }
    };
    org.breezee.page.init();
});